<template>
  <div>
    <el-upload
      action=""
      :auto-upload="false"
      :show-file-list="false"
      :on-change="handleFileUpload"
      accept=".xlsx,.xls"
    >
      <template #trigger>
        <el-button type="primary" style="margin-right: 10px">
          上传 Excel
        </el-button>
      </template>

      <el-button type="success" @click="download" plain>下载pdf</el-button>
    </el-upload>

    <hr style="margin-bottom: 20px" />
    <!-- 渲染 Excel 生成的 HTML 表格 -->
    <div id="output" v-html="tableHtml" />
  </div>
</template>

<script setup>
import { ref } from "vue";
import * as ExcelJS from "exceljs";
import { downloadPDF } from "./tool.js";

const pdfName = ref("test");
const download = () => {
  downloadPDF(document.querySelector("#output"), pdfName.value);
};

// const commonStyle = '<style>td { border: 1px solid #000;}</style>';
const commonStyle = "<style></style>";
const tableHtml = ref(""); // 存储 HTML 表格内容
const themeColors = {
  0: "#D9D9D9", // 灰色
  1: "#FFFFFF", // 白色
  2: "#1F4E79", // 深蓝
  3: "#4F81BD", // 蓝色
  4: "#D9E1F4", // 浅蓝
  5: "#F9CBAA", // 橙色
  6: "#00FF00", // 浅绿
  7: "#E46C0A", // 橙色
  8: "#F79646", // 浅橙
  9: "#FF0000", // 红色
  10: "#FFC7CE", // 浅红
  11: "#7030A0", // 紫色
};
// 获取单元格颜色
const getCellColor = (cell) => {
  if (cell.fill && cell.fill.fgColor) {
    if (cell.fill.fgColor.argb) {
      return `#${cell.fill.fgColor.argb.substring(2)}`; // ARGB 转 RGB
    }
    if (cell.fill.fgColor.theme !== undefined) {
      return themeColors[cell.fill.fgColor.theme] || "#FFFFFF"; // 主题色转换
    }
  }

  return ""; // 无颜色
};
// 获取单元格字体颜色
const getCellFontColor = (cell) => {
  if (cell.font && cell.font.color && cell.font.color.argb) {
    return `#${cell.font.color.argb.substring(2)}`; // ARGB 转 RGB
  }
  if (cell.font && cell.font.color && cell.font.color.theme) {
    switch (cell.font.color.theme) {
      case 0:
        return "#fff"; // 白色
      case 1:
        return "#000"; // 默认黑色
      default:
        return "#000"; // 默认黑色
    }
  }

  return "#000"; // 默认黑色
};
const handleStyles = (cell) => {
  const styles = [];

  // 读取字体颜色
  styles.push(`color: ${getCellFontColor(cell)}`);
  // 读取背景色
  styles.push(`background-color: ${getCellColor(cell)}`);

  // 加粗
  if (cell.font && cell.font.bold) {
    styles.push("font-weight: bold");
  }

  // 文字对齐
  if (cell.alignment) {
    if (cell.alignment.horizontal) {
      styles.push(`text-align: ${cell.alignment.horizontal}`);
    }
    if (cell.alignment.vertical) {
      styles.push(`vertical-align: ${cell.alignment.vertical}`);
    }
  }

  return styles.join("; ");
};

// 处理单元格内容
const handleValue = (value) => {
  if (value && typeof value === "object" && value.richText) {
    console.log("value.richText", value.richText);
    // const valueArr =  value.richText.map((textPart) => textPart.text)
    const valueArr = value.richText.reduce((acc, curr) => {
      let colorValue = "";
      if (curr.font && curr.font.color && curr.font.color.argb) {
        colorValue = `#${curr.font.color.argb.substring(2)}`;
      } else {
        colorValue = `#000`;
      }

      const newData = curr.text
        .split(/\r?\n/)
        .map((item) => `<p style="color:${colorValue}">${item}</p>`);
      return acc.concat(newData);
    }, []);

    return valueArr.join("");
  }

  return value ? value : "";
};

// 处理上传的 Excel 文件
const handleFileUpload = async (file) => {
  const excelData = await readExcel(file.raw);
  tableHtml.value = excelData; // 更新 HTML 表格内容
};

let rowStyles = {
  4: `padding:10px;background-color: red`,
};

let tableSize = [
  [1, 13],
  [15, 24],
  [26, 42],
];
const handleTable = (worksheet, merges, index) => {
  console.log("worksheetindex", index);
  let html = "<html>";
  html += commonStyle;
  html += '<div style="margin-bottom: 10px;padding:10px;">';
  html += '<table border="1" style="border-collapse: collapse;">';

  console.log("worksheet.eachRow1111", worksheet.eachRow);
  worksheet.eachRow((row, rowIndex) => {
    console.log(rowIndex, "rowIndex");
    if (rowIndex >= tableSize[index][0] && rowIndex <= tableSize[index][1]) {
      html += `<tr>`;

      row.eachCell((cell, colIndex) => {
        console.log(cell, "cellcellcell");
        let cellValue = cell.value || "";
        console.log(cellValue, "cellValuecellValue111");

        // 处理合并单元格
        let rowspan = 1,
          colspan = 1;
        let isMerged = false;

        for (let merge of merges) {
          // console.log(merges, 'mergesmergesmerges')
          // console.log(cellValue, 'cellValuecellValue------mergemergemerge')
          const [start, end] = merge.split(":");
          const startCell = worksheet.getCell(start);
          const endCell = worksheet.getCell(end);
          const startRow = startCell.row,
            startCol = startCell.col;
          const endRow = endCell.row,
            endCol = endCell.col;

          if (startRow === rowIndex && startCol === colIndex) {
            rowspan = endRow - startRow + 1;
            colspan = endCol - startCol + 1;
            isMerged = true;

            const styles = handleStyles(cell);
            html += `<td rowspan="${rowspan}" colspan="${colspan}" style="${styles}">${handleValue(
              startCell.value
            )}</td>`;
            break;
          }
          if (
            rowIndex >= startRow &&
            rowIndex <= endRow &&
            colIndex >= startCol &&
            colIndex <= endCol
          ) {
            isMerged = true;
            break;
          }
        }

        if (!isMerged) {
          const styles = handleStyles(cell);
          console.log(cellValue, "cellValuecellValue222");
          // 生成 HTML 单元格
          html += `<td ${rowspan > 1 ? `rowspan="${rowspan}"` : ""} ${
            colspan > 1 ? `colspan="${colspan}"` : ""
          } style="${styles}">${cellValue}</td>`;
        }
      });

      html += "</tr>";
    }
  });

  html += "</table></div></html>";

  return html;
};
// 读取 Excel 并转换成 HTML
const readExcel = async (file) => {
  const workbook = new ExcelJS.Workbook();
  const arrayBuffer = await file.arrayBuffer();
  await workbook.xlsx.load(arrayBuffer);
  const worksheet = workbook.getWorksheet(1); // 读取第一个工作表

  // 处理合并单元格
  const merges = worksheet.model.merges || [];
  console.log("merges", merges);
  let html = "";
  for (let i = 0; i < tableSize.length; i++) {
    const htmlStr = handleTable(worksheet, merges, i);
    html += htmlStr;
  }

  return html;
};
</script>

<style scoped></style>
